package com.kongwg.java2;

import com.kongwg.java1.Person;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author kongwg
 * @create 2020-12-24 20:39
 */
public class MethedTest {

    //获取运行时类的方法结构
    //获得运行类和父类的public的方法
    @Test
    public void test1() {

        Class<Person> clazz = Person.class;
        Method[] methods = clazz.getMethods();
        for (Method m : methods) {
            System.out.println(m);
        }

        System.out.println("************");
        Method[] methodss = clazz.getDeclaredMethods();

        for (Method m : methodss) {
            System.out.println(m);
        }
    }

    /*
@Xxxx
权限修饰符  返回值类型  方法名(参数类型1 形参名1,...) throws XxxException{}
 */
    @Test
    public void test2() {
        Class<Person> clazz = Person.class;

        Method[] methods = clazz.getDeclaredMethods();
        for (Method m : methods){
            //获取注解
            Annotation[] annotations = m.getAnnotations();
            for (Annotation a : annotations){
                System.out.println(a);
            }
            //权限修饰符
            int modifiers = m.getModifiers();
            System.out.print(Modifier.toString(modifiers) + "\t");
            //返回值类型
            Class<?> returnType = m.getReturnType();
            System.out.print(returnType + "\t");

            //方法名
            String name = m.getName();
            System.out.print(name);
            Class<?>[] parameterTypes = m.getParameterTypes();
            System.out.print("(");
            if (!(parameterTypes == null && parameterTypes.length == 0)){
                for (int i = 0; i < parameterTypes.length; i++) {
                    if (i == parameterTypes.length -1){
                        System.out.print(parameterTypes[i].getName() + "args_" + i);
                        break;
                    }
                    System.out.print(parameterTypes[i] + "args_" + i +",");
                }
            }
            System.out.print(")");
            //异常

            Class<?>[] exceptionTypes = m.getExceptionTypes();
            if (exceptionTypes.length > 0){
                System.out.print("throws ");
                for (int i = 0; i < exceptionTypes.length; i++) {
                    if (i == exceptionTypes.length){
                        System.out.println(exceptionTypes[i]);
                    }
                    System.out.println(exceptionTypes[i] + ",");
                }

            }
            System.out.println();
        }

    }

}
